﻿package cn.poco.pepsi.activity.init;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import cn.poco.pepsi.R;
import cn.poco.pepsi.TabActivity;
import cn.poco.pepsi.adapter.AdapterSwitchCityList;
import cn.poco.pepsi.bean.City;
import cn.poco.pepsi.service.impl.CityImpl;
import cn.poco.pepsi.util.Cons;
import cn.poco.pepsi.util.GpsLocationUtil;

public class SwitchCityActivity extends Activity {
	public final static String TAG = "SwitchCityActivity";
	private final static int CITY_SUCCESS = 1;
	private AdapterSwitchCityList adapter;
	private LinearLayout error;
	private Button tautology;
	private Button setBtn;
	private ListView cityListView;
	private LinearLayout progressbar;
	private List<City> list;
	private SharedPreferences sp;
	private Handler myHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.switch_city);
		cityListView = (ListView) findViewById(R.id.listview);
		progressbar = (LinearLayout) findViewById(R.id.progressbar);
		error = (LinearLayout) findViewById(R.id.error);
		error.setVisibility(View.GONE);
		tautology = (Button) findViewById(R.id.tautology);
		setBtn = (Button) findViewById(R.id.setnet);
		sp = SwitchCityActivity.this.getSharedPreferences(Cons.GPS_CITY_CODE, Context.MODE_PRIVATE);

		cityListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == 5 && list.get(position).getKey() == "000000") {
					list.remove(list.get(list.size() - 1));
					list.remove(position);
					adapter.notifyDataSetChanged();
				} else {
					if (!list.get(position).getKey().equals("222222")) {
						String cityCode= list.get(position).getKey();
						
						Intent intent = new Intent(SwitchCityActivity.this, TabActivity.class);
						intent.putExtra(Cons.CITY_CODE, list.get(position).getKey());
						intent.putExtra(Cons.CITY_NAME, list.get(position).getName());
						Editor editor = sp.edit();
						editor.putString(Cons.CITY_CODE, list.get(position).getKey());
						editor.putString(Cons.CITY_NAME, list.get(position).getName());
						editor.commit();
						
						/*
						Intent intentStartService = new Intent(SwitchCityActivity.this, DownloadAreaAndDish.class);
						intentStartService.putExtra(Cons.CITY_CODE, cityCode);
						startService(intentStartService);
						 * 
						 */

						startActivity(intent);
						SwitchCityActivity.this.finish();
					}
				}
			}
		});

		// 设置网络
		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});

		// 重试按钮
		tautology.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				progressbar.setVisibility(View.VISIBLE);
				error.setVisibility(View.GONE);
				myHandler.post(new GetCity());
			}
		});

		HandlerThread handlerThread = new HandlerThread(TAG);
		handlerThread.start();
		myHandler = new Handler(handlerThread.getLooper());
		myHandler.post(new GetCity());

	}

	public class GetCity implements Runnable {
		@Override
		public void run() {
			try {
				list = new CityImpl().switchCity(SwitchCityActivity.this);
				if (list != null) {
					handler.sendEmptyMessage(CITY_SUCCESS);
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendEmptyMessage(Cons.CONN_ERROR);
			}
		}
	}

	private final class UpdateGpsInfo implements Runnable {
		private Double lat;
		private Double lon;

		public UpdateGpsInfo(Double lat, Double lon) {
			this.lat = lat;
			this.lon = lon;
		}

		@Override
		public void run() {
			CityImpl icity = new CityImpl();
			City city = new City();
			try {
				city = icity.switchCitybyGps(lat, lon);
			} catch (Exception e) {
				e.printStackTrace();
			}
			list.remove(0);
			list.add(0, city);
			Message msg = new Message();
			msg.what = Cons.GPS_UPDATE;
			Bundle bundle = new Bundle();
			bundle.putString(Cons.CITY_NAME, city.getName());
			bundle.putString(Cons.CITY_CODE, city.getKey());
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CITY_SUCCESS:
				progressbar.setVisibility(View.GONE);
				City more3 = new City();
				more3.setKey("222222");
				more3.setName("正在定位...");
				list.add(0, more3);
				City more = new City();
				more.setKey("000000");
				more.setName("更多");
				list.add(5, more);
				City more2 = new City();
				more2.setKey("111111");
				more2.setName("flag");
				list.add(more2);
				adapter = new AdapterSwitchCityList(SwitchCityActivity.this, list);
				cityListView.setAdapter(adapter);
				cityListView.setVisibility(View.VISIBLE);
				//GpsLocationUtil.getInstance(SwitchCityActivity.this).getLocation(handler);
				
				break;
			case Cons.GPS_LOCATION_CHANGE:
				/*GpsLocationUtil.getInstance(SwitchCityActivity.this).unRequestListener();
				Bundle bundle = msg.getData();
				Double lat = bundle.getDouble(Cons.GPS_LAT);
				Double lon = bundle.getDouble(Cons.GPS_LONG);*/
				//*************虚拟坐标***************************
				Double lat = 23.1043250;
				Double lon =113.2611950;
				myHandler.post(new UpdateGpsInfo(lat, lon));
				break;

			case Cons.GPS_UPDATE:
				adapter.notifyDataSetChanged();
				Bundle b = msg.getData();
				Editor dEditor = sp.edit();
				dEditor.putString(Cons.CITY_CODE, b.getString(Cons.CITY_CODE));
				dEditor.putString(Cons.CITY_NAME, b.getString(Cons.CITY_NAME));
				dEditor.commit();
				break;

			case Cons.NO_GPS:
				new AlertDialog.Builder(SwitchCityActivity.this).setTitle("错误")
						.setMessage("没有打开GPS设置,无法获取您的位置信息，现在开启?").setNegativeButton("取消", null).setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
									}
								}).show();
				break;

			case Cons.CONN_ERROR:
				progressbar.setVisibility(View.GONE);
				cityListView.setVisibility(View.GONE);
				error.setVisibility(View.VISIBLE);
				break;
			}

		};
	};

	@Override
	protected void onPause() {
		super.onPause();
		GpsLocationUtil gpsLocationUtil=GpsLocationUtil.getInstance(SwitchCityActivity.this);
		if (gpsLocationUtil!=null) {
			gpsLocationUtil.unRequestListener();
		}
	}

}
